package com.cucn.ingmall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cucn.common.constant.auth.SmsConstant;
import com.cucn.common.to.dto.MemberResponseDTO;
import com.cucn.common.utils.HttpUtils;
import com.cucn.common.utils.R;
import com.cucn.ingmall.auth.feign.MemberFeignService;
import com.cucn.ingmall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录请求controller
 *
 * @author KouChaoJie
 * @since: 2022/1/11 14:40
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Resource
    private MemberFeignService memberFeignService;

    @Value("${gitee.grant-type}")
    private String grantType;
    @Value("${gitee.client-id}")
    private String clientId;
    @Value("${gitee.redirect-uri}")
    private String redirectUri;
    @Value("${gitee.client-secret}")
    private String clientSecret;

    /**
     * gitee社交登录请求
     *
     * @param code code码
     * @return 登录成功跳转到首页
     */
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        log.info("code:{}", code);
        Map<String, String> param = new HashMap<>();
        param.put("grant_type", grantType);
        param.put("code", code);
        param.put("client_id", clientId);
        param.put("redirect_uri", redirectUri);
        param.put("client_secret", clientSecret);
        //用code换取AccessToken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), param, new HashMap<>());

        //处理token
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了返参,转换成实体类
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //拿到token,知道当前是哪个社交用户
            //远程调用,由member服务判断是否是第一次登录
            log.info("社交登录,发送给远程服务进行调用...token:{}", socialUser.getAccess_token());
            R r = memberFeignService.login(socialUser);
            if (r.getCode() == 0) {
                //成功
                MemberResponseDTO memberResponseDTO = r.getData("data", new TypeReference<MemberResponseDTO>() {
                });

                log.info("用户:{}..登录成功,跳转到首页....", memberResponseDTO);
                session.setAttribute(SmsConstant.LOGIN_USER,memberResponseDTO);

                return "redirect:http://ingmall.koukoucoding.xn--fiqs8s/";
            } else {
                //失败
                return "redirect:http://auth.koukoucoding.xn--fiqs8s/login.html";
            }
        } else {
            return "redirect:http://auth.koukoucoding.xn--fiqs8s/login.html";
        }
    }
}
